from pymt import *
import os
import random
from OpenGL.GL import *
import copy
import Image
import MTZone as MTZone
import MTButtonsZone as MTButtonsZone
current_dir = os.path.dirname(__file__)

class MTMediaZone(MTZone.MTZone):

    def __init__(self, **kwargs):
        print "MTMediaZone constructed"
        self.grow_delta = Vector(0, 0)		
        self.selected=False
        self.type='MTMediaZone'
        self.resize_controls_touches = {}		
        super(MTMediaZone, self).__init__(cls=self.type,**kwargs)	
        self.add_resize_controls()
        self.add_buttons_zone()		
        self.hide_resize_controls()
        self.hide_buttons_zone()		
        self.move=False
        self.hold=False
        self.btn_visible=False			
        self.dx=0
        self.dy=0		
        
		
    def add_resize_controls(self):
        scaled_border = self.get_scaled_border()
		
        self.resize_controls = MTWidget()
        self.add_widget(self.resize_controls)		
		
        self.control_top_left = MTButton(size=(30,30), pos=(-22, self.height-8),cls="resizeControlsMedia")
        self.control_bottom_left = MTButton(size=(30,30), pos=(-22, -22), cls="resizeControlsMedia")
        self.control_top_right = MTButton(size=(30,30), pos=(self.width-8, self.height-8), cls="resizeControlsMedia")
        self.control_bottom_right = MTButton(size=(30,30), pos=(self.width-8, -22), cls="resizeControlsMedia")
        self.control_top_middle = MTButton(size=(30,30), pos=((self.width/2)-15, self.height-8),cls="resizeControlsMedia")
        self.control_bottom_middle = MTButton(size=(30,30), pos=((self.width/2)-15, -22), cls="resizeControlsMedia")
        self.control_right_middle = MTButton(size=(30,30), pos=((self.width)-8, (self.height/2)-15), cls="resizeControlsMedia")
        self.control_left_middle = MTButton(size=(30,30), pos=(-22, (self.height/2)-15), cls="resizeControlsMedia")
        
        self.resize_controls.add_widget(self.control_top_left)
        self.resize_controls.add_widget(self.control_bottom_left)
        self.resize_controls.add_widget(self.control_top_right)
        self.resize_controls.add_widget(self.control_bottom_right)
        self.resize_controls.add_widget(self.control_top_middle)
        self.resize_controls.add_widget(self.control_bottom_middle)
        self.resize_controls.add_widget(self.control_right_middle)
        self.resize_controls.add_widget(self.control_left_middle) 		
    
    def hide_resize_controls(self):
        self.resize_controls.visible = False

    def show_resize_controls(self):
        self.resize_controls.visible = True

    def add_buttons_zone(self):
        self.buttons_zone=MTButtonsZone.MTButtonsZone(type="media", parent=self)
        self.add_widget(self.buttons_zone)
        self.buttons_zone.width = self.width		
		
    def hide_buttons_zone(self):
        self.buttons_zone.visible = False

    def show_buttons_zone(self):
        self.buttons_zone.visible = True
        self.buttons_zone.bring_to_front()			
    
    def on_touch_down (self, touch):	
		if not self.collide_point(touch.x, touch.y):
			MTZone.MTZone.on_touch_down(self, touch)
			return False

		local_touch = self.to_local(touch.x, touch.y)
		self.dx=touch.x-self.center[0]
		self.dy=touch.y-self.center[1]
		if touch.is_double_tap and self.btn_visible==False:
			self.show_buttons_zone()
			self.btn_visible=True			
		elif touch.is_double_tap and self.btn_visible==True:
			self.hide_buttons_zone()
			self.btn_visible=False			
		if self.selected==True:		
			if(len(self.resize_controls_touches.keys()) == 0): # only one touch allowed at a time on the aspect ratio controls
				self.move=False		 
				if(self.control_top_left.collide_point(local_touch[0], local_touch[1])):
					print "touch top left"
					self.resize_controls_touches[touch.id] = ["top", "left"]
				
				elif(self.control_bottom_left.collide_point(local_touch[0], local_touch[1])):
					print "touch bottom left"					
					self.resize_controls_touches[touch.id] = ["bottom", "left"]
				
				elif(self.control_top_right.collide_point(local_touch[0], local_touch[1])):
					print "touch top right"					
					self.resize_controls_touches[touch.id] = ["top", "right"]
				
				elif(self.control_bottom_right.collide_point(local_touch[0], local_touch[1])):
					print "touch bottom right"					
					self.resize_controls_touches[touch.id] = ["bottom", "right"]
				   
				elif(self.control_top_middle.collide_point(local_touch[0], local_touch[1])):
					print "touch top middle"					
					self.resize_controls_touches[touch.id] = ["top", "middle"]
				
				elif(self.control_bottom_middle.collide_point(local_touch[0], local_touch[1])):
					print "touch bottom middle"					
					self.resize_controls_touches[touch.id] = ["bottom", "middle"]
				
				elif(self.control_right_middle.collide_point(local_touch[0], local_touch[1])):
					print "touch right middle"					
					self.resize_controls_touches[touch.id] = ["right", "middle"]
				
				elif(self.control_left_middle.collide_point(local_touch[0], local_touch[1])):
					print "touch left middle"					
					self.resize_controls_touches[touch.id] = ["left", "middle"]

				else:
					print "MTMediaZone touch down NOT over resize controls"
					self.move=True

			return MTZone.MTZone.on_touch_down(self, touch)
	
    def on_touch_up (self, touch):
		self.hold=False		
		if(touch.id in self.resize_controls_touches.keys()):
			del self.resize_controls_touches[touch.id]
			return MTZone.MTZone.on_touch_up(self, touch) 			
		if not self.collide_point(touch.x, touch.y):
			if self.selected==True:
				self.hide_resize_controls()
				self.selected=False
			MTZone.MTZone.on_touch_up(self, touch) 
			return False
		elif self.selected==False:
			self.selected=True
			self.bring_to_front()			
			self.show_resize_controls()
		return MTZone.MTZone.on_touch_up(self, touch)       	


    def on_touch_move (self, touch):
		if not self.collide_point(touch.x, touch.y):
			MTZone.MTZone.on_touch_move(self, touch)
			return False	
		if self.hold !=True and self.move==True and self.selected==True: 
			self.center=(touch.x-self.dx,touch.y-self.dy)
		return MTZone.MTZone.on_touch_move(self, touch)

    def on_transform(self, angle, scale, trans, point):
        self.update_resize_controls()
        self.update_resize_content()
        self.update_resize_buttons()
        MTButtonsZone.MTButtonsZone.on_transform(self.buttons_zone, angle, scale, trans, point)

    def update_resize_buttons(self):
        self.buttons_zone.height = 40
        self.buttons_zone.width = self.width

    def update_resize_controls(self):
        #hack to lock the window controls to stay the same size when the window is resized
        for child in self.resize_controls.children:
            child.scale = 1.0 / self.scale # do not scale the aspect controls

        self.control_top_left.pos = -22, self.height-8
        self.control_bottom_left.pos = -22, -22
        self.control_top_right.pos = self.width-8, self.height-8
        self.control_bottom_right.pos = self.width-8, -22
        self.control_top_middle.pos = (self.width/2)-15, self.height-8
        self.control_bottom_middle.pos = (self.width/2)-15, -22
        self.control_right_middle.pos = self.width-8, (self.height/2)-15
        self.control_left_middle.pos = -22, (self.height/2)-15

    def update_resize_content(self):
		if (self.content !=None):
			self.content.size=self.size	

    def update_resize_container(self):
			self.container.size=self.size				
		
    def apply_angle_scale_trans(self, angle, scale, trans, point=Vector(0, 0)):      
        if(len(self.resize_controls_touches.keys()) >= 1 and len(self.touches) == 1):    # change size rather than scale
            grow_delta = Vector(trans.x, trans.y)
            grow_delta = grow_delta.rotate(360.0 - self.rotation)

            resize_control_location = self.resize_controls_touches.items()[0][1]
			
            # handle switch in direction of growth
            # left
            if("left" in resize_control_location):
                grow_delta[0] *= -1.0
            # bottom
            if("bottom" in resize_control_location):
                grow_delta[1] *= -1.0
            
            old_width=self.width
            old_height=self.height
			
			# change the size
            if("middle" in resize_control_location and ("left" in resize_control_location or "right" in resize_control_location)):
                self.width += grow_delta[0]
            elif("middle" in resize_control_location and ("top" in resize_control_location or "bottom" in resize_control_location)):
                self.height += grow_delta[1]			
            else:
                if (self.content!=None):
					if (self.width+grow_delta[0] > self.height+grow_delta[1]):
						self.width += grow_delta[0]
						self.height=self.height*(self.width/old_width)
					else:
						self.height += grow_delta[1]
						self.width=self.width*(self.height/old_height)						
                else:
					self.width += grow_delta[0]
					self.height += grow_delta[1]

            # offset the window
            trans.x = 0
            trans.y = 0
			
            # left
            if("left" in resize_control_location):
                trans.x = -grow_delta[0]
            # bottom
            if("bottom" in resize_control_location):
                trans.y = -grow_delta[1]
            
            print trans.x, trans.y
			# check that the widget isn't too small or too large
            if(self.height <= self.height_min):
                print "height too small"
                self.height = self.height_min
                if (self.content!=None):
					self.width = old_width				
            elif(self.height >= self.height_max):
                print "height too big"			
                self.height = self.height_max
                if (self.content!=None):
					self.width = old_width					
            if(self.width <= self.width_min):
                print "width too small"			
                self.width = self.width_min
                if (self.content!=None):
					self.height = old_height					
            elif(self.width >= self.width_max):
                print "width too big"
                self.width = self.width_max
                if (self.content!=None):
					self.height = old_height
            # resize the widget's container too
            self.container.height = self.height
            self.container.width = self.width

            scale = 0
            rotate = 0
            
            self.dispatch_event('on_transform', angle, scale, trans, point)

        angle=0
        scale=0
        MTScatterWidget.apply_angle_scale_trans(self, angle, scale, trans, point)
			
    def draw(self):
        MTZone.MTZone.draw(self)
        self.resize_controls.bring_to_front()
        self.buttons_zone.bring_to_front()		
        self.resize_controls.dispatch_event('on_draw')